<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>搜索条件</span>
          <el-button link type="primary" @click="toggleFilterExpand">
            {{ filterExpanded ? '收起' : '展开' }}
            <el-icon>
              <ArrowDown v-if="!filterExpanded" />
              <ArrowUp v-else />
            </el-icon>
          </el-button>
        </div>
      </template>

      <div class="filter-container" :class="{ 'filter-collapsed': !filterExpanded }">
        <el-form :inline="true" :model="queryParams" @keyup.enter="handleQuery">
          <el-form-item label="货物单号">
            <el-input v-model="queryParams.number_no" placeholder="请输入货物单号" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><Document /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="取货仓库">
            <el-input v-model="queryParams.pickup_warehouse" placeholder="请输入取货仓库" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><House /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="卸货仓库">
            <el-input v-model="queryParams.delivery_warehouse" placeholder="请输入卸货仓库" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><OfficeBuilding /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="设备号">
            <el-input v-model="queryParams.mac_id" placeholder="请输入设备号" clearable @clear="handleQuery">
              <template #prefix>
                <el-icon><Cpu /></el-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @clear="handleQuery">
              <el-option label="未开始" :value="0" />
              <el-option label="进行中" :value="10" />
              <el-option label="已完成" :value="30" />
              <el-option label="异常" :value="-10" />
            </el-select>
          </el-form-item>
          <el-form-item class="search-buttons-container">
            <div class="search-buttons">
              <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
              <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>货物列表</span>
        </div>
      </template>

      <div class="table-container">
        <div class="table-toolbar">
          <div class="left-buttons">
            <el-button type="primary" :icon="Plus" @click="handleAdd">新增货物</el-button>
          </div>
        </div>

        <el-table 
          v-loading="loading" 
          :data="shipmentList" 
          size="default"
          border 
          stripe
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="number_no" label="货物单号" min-width="120" show-overflow-tooltip />
          <el-table-column prop="pickup_warehouse" label="取货仓库" min-width="120" show-overflow-tooltip />
          <el-table-column prop="delivery_warehouse" label="卸货仓库" min-width="120" show-overflow-tooltip />
          <el-table-column prop="mac_id" label="设备号" min-width="120" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status === 0" type="info" effect="light">未开始</el-tag>
              <el-tag v-else-if="scope.row.status === 10" type="warning" effect="light">进行中</el-tag>
              <el-tag v-else-if="scope.row.status === 30" type="success" effect="light">已完成</el-tag>
              <el-tag v-else-if="scope.row.status === -10" type="danger" effect="light">异常</el-tag>
              <el-tag v-else type="info" effect="light">未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260" fixed="right" align="center">
            <template #default="scope">
              <div class="table-operation-buttons">
                <router-link :to="`/shipment/route/${scope.row.id}`" v-if="scope.row.status === 10 || scope.row.status === 30">
                  <el-button type="success" link :icon="MapLocation">路线</el-button>
                </router-link>
                <el-button type="warning" link :icon="Edit" @click="handleEdit(scope.row)">编辑</el-button>
                <el-popconfirm
                  :title="`确认删除货物 ${scope.row.number_no} 吗?`"
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  @confirm="handleDelete(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger" link :icon="Delete">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="pagination"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          background
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="550px" 
      destroy-on-close
      center
      align-center
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-form ref="shipmentFormRef" :model="shipmentForm" :rules="shipmentRules" label-width="100px" status-icon>
        <el-form-item label="货物单号" prop="number_no">
          <el-input v-model="shipmentForm.number_no" placeholder="请输入货物单号">
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="取货仓库" prop="pickup_warehouse">
          <el-input v-model="shipmentForm.pickup_warehouse" type="textarea" :rows="3" placeholder="请输入取货仓库">
          </el-input>
        </el-form-item>
        <el-form-item label="卸货仓库" prop="delivery_warehouse">
          <el-input v-model="shipmentForm.delivery_warehouse" type="textarea" :rows="3" placeholder="请输入卸货仓库">
          </el-input>
        </el-form-item>
        <el-form-item label="设备号" prop="mac_id">
          <el-input v-model="shipmentForm.mac_id" placeholder="请输入设备号">
            <template #prefix>
              <el-icon><Cpu /></el-icon>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Plus, Edit, Delete, Search, Refresh, MapLocation, 
  ArrowDown, ArrowUp, Document, Cpu
} from '@element-plus/icons-vue'
import { getShipments, getShipment, createShipment, updateShipment, deleteShipment } from '@/api/shipment'

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  number_no: '',
  pickup_warehouse: '',
  delivery_warehouse: '',
  mac_id: '',
  status: null
})

// 表单对象
const shipmentForm = reactive({
  id: undefined,
  number_no: '',
  pickup_warehouse: '',
  delivery_warehouse: '',
  mac_id: '',
  status: 0,
  version: 1
})

// 表单校验规则
const shipmentRules = {
  number_no: [{ required: true, message: '货物单号不能为空', trigger: 'blur' }],
  pickup_warehouse: [{ required: true, message: '取货仓库不能为空', trigger: 'blur' }],
  delivery_warehouse: [{ required: true, message: '卸货仓库不能为空', trigger: 'blur' }],
  mac_id: [{ required: true, message: '设备号不能为空', trigger: 'blur' }]
}

// 数据列表
const shipmentList = ref([])
const total = ref(0)
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const shipmentFormRef = ref()
const submitLoading = ref(false)

// UI控制变量
const filterExpanded = ref(true)

// 切换筛选器展开/收起
const toggleFilterExpand = () => {
  filterExpanded.value = !filterExpanded.value
}

// 获取货物列表
const getShipmentList = async () => {
  loading.value = true
  try {
    const params = {
      skip: (queryParams.pageNum - 1) * queryParams.pageSize,
      limit: queryParams.pageSize,
      number_no: queryParams.number_no.trim() || undefined,
      pickup_warehouse: queryParams.pickup_warehouse.trim() || undefined,
      delivery_warehouse: queryParams.delivery_warehouse.trim() || undefined,
      mac_id: queryParams.mac_id.trim() || undefined,
      status: queryParams.status === null ? undefined : queryParams.status
    }
    
    const res = await getShipments(params)
    shipmentList.value = res.data || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取货物列表失败:', error)
    ElMessage.error('获取货物列表失败')
  } finally {
    loading.value = false
  }
}

// 查询
const handleQuery = () => {
  queryParams.pageNum = 1
  getShipmentList()
}

// 重置查询
const resetQuery = () => {
  queryParams.number_no = ''
  queryParams.pickup_warehouse = ''
  queryParams.delivery_warehouse = ''
  queryParams.mac_id = ''
  queryParams.status = null
  queryParams.pageNum = 1
  getShipmentList()
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getShipmentList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  getShipmentList()
}

// 添加货物
const handleAdd = () => {
  resetForm()
  dialogTitle.value = '添加货物信息'
  dialogVisible.value = true
}

// 编辑货物
const handleEdit = async (row) => {
  resetForm()
  dialogTitle.value = '编辑货物信息'
  
  try {
    const res = await getShipment(row.id)
    Object.assign(shipmentForm, res.data)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取货物详情失败:', error)
    ElMessage.error('获取货物详情失败')
  }
}

// 删除货物
const handleDelete = async (row) => {
  try {
    await deleteShipment(row.id)
    ElMessage.success('删除成功')
    getShipmentList()
  } catch (error) {
    console.error('删除货物失败:', error)
    ElMessage.error('删除货物失败')
  }
}

// 重置表单
const resetForm = () => {
  shipmentForm.id = undefined
  shipmentForm.number_no = ''
  shipmentForm.pickup_warehouse = ''
  shipmentForm.delivery_warehouse = ''
  shipmentForm.mac_id = ''
  shipmentForm.status = 0
  shipmentForm.version = 1
  
  if (shipmentFormRef.value) {
    shipmentFormRef.value.resetFields()
  }
}

// 提交表单
const submitForm = () => {
  shipmentFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (shipmentForm.id) {
          // 编辑
          const response = await updateShipment(shipmentForm.id, shipmentForm)
          
          // 根据后端返回的消息显示详细信息
          if (response.message) {
            ElMessage.success(response.message)
          } else {
            ElMessage.success('修改成功')
          }
        } else {
          // 新增
          const response = await createShipment(shipmentForm)
          
          // 根据后端返回的消息显示详细信息
          if (response.message) {
            ElMessage.success(response.message)
          } else {
            ElMessage.success('添加成功')
          }
        }
        dialogVisible.value = false
        getShipmentList()
      } catch (error) {
        console.error('保存货物信息失败:', error)
        ElMessage.error('保存货物信息失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

onMounted(() => {
  getShipmentList()
})
</script>

<style lang="scss" scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-container {
  transition: max-height 0.3s ease-in-out, opacity 0.3s ease-in-out;
  max-height: 300px;
  overflow: hidden;
  opacity: 1;
  
  &.filter-collapsed {
    max-height: 0;
    opacity: 0;
  }
}

.table-operation-buttons {
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  gap: 5px;
  
  .el-button {
    margin: 0;
  }
}
</style>